package com.jackchong.widget

import android.content.Context
import android.util.AttributeSet
import android.content.res.TypedArray
import com.utils.R
import android.view.View
import android.view.ViewGroup
import androidx.constraintlayout.widget.ConstraintLayout

/**
 * author : chong.huang
 * create : 2/9/21
 * desc   :
 */
class JConstraintLayout @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) : ConstraintLayout(context, attrs, defStyleAttr) {

    private var mJAutoPress = false
    private var mJRadio = false


    init {
        val typedArray = context.obtainStyledAttributes(attrs, R.styleable.JConstraintLayout)
        parseAttr(typedArray)
        typedArray.recycle()
    }

    private fun parseAttr(typedArray: TypedArray) {
        mJRadio = typedArray.getBoolean(R.styleable.JConstraintLayout_JRadio, false)
        mJAutoPress = typedArray.getBoolean(R.styleable.JConstraintLayout_JAutoPress, false)
    }

    override fun onFinishInflate() {
        super.onFinishInflate()
        if (mJRadio) {
            radio()
        }
    }

    override fun addView(child: View, index: Int, params: ViewGroup.LayoutParams) {
        super.addView(child, index, params)
        if (mJRadio) {
            radio()
        }
    }

    override fun removeView(view: View) {
        super.removeView(view)
        if (mJRadio) {
            radio()
        }
    }

    override fun removeViewAt(index: Int) {
        super.removeViewAt(index)
        if (mJRadio) {
            radio()
        }
    }

    private fun radio() {
        for (i in 0 until childCount) {
            val view = getChildAt(i)
            view.setOnClickListener { v: View? ->
                for (j in 0 until childCount) {
                    getChildAt(j).isSelected = i == j
                }
            }
        }
    }

    override fun setPressed(pressed: Boolean) {
        super.setPressed(pressed)
        val alpha = if (pressed && isClickable) 0.8f else 1f
        if (mJAutoPress && alpha != getAlpha()) {
            setAlpha(alpha)
        }
    }
}